<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-form :model="spuInfo" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择" v-model="(spuInfo.tmId as number)">
          <el-option
            v-for="tm in tmList"
            :key="tm.id"
            :value="tm.id"
            :label="tm.tmName"
          />
          >
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="SPU名称"
          rows="4"
          v-model="spuInfo.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          v-model:file-list="(spuImageList as UploadUserFile[])"
          :action="`${baseUrl}/admin/product/upload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-select
          :placeholder="`${saleAttrListCompute.length}个未选`"
          v-model="tempSaleAttr"
        >
          <!-- <el-option
          v-for="attr in saleAttrList"
          :key="attr.id"
          :value="attr.id as number"></el-option>
        </el-select> -->
          <el-option
            v-for="attr in saleAttrListCompute"
            :key="attr.id"
            :label="attr.name"
            :value="`${attr.id}:${attr.name}`"
          />
        </el-select>
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          @click="handleAddSaleAttr"
          :disabled="!saleAttrListCompute.length"
          >添加销售属性</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-table :data="spuSaleAttrList" border stripe>
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性值名称列表">
            <template v-slot="{ row }">
              <!-- @close="handleClose(tag)" -->
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                class="mx-1"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!-- @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm" -->
              <el-input
                v-model="row.inputValue"
                class="ml-1 w-20"
                size="small"
                ref="editEle"
                v-if="row.isEdit"
                @blur="handleSwitahText(row)"
                @keydown.enter=""
              />
              <el-button
                class="button-new-tag ml-1"
                size="small"
                @click="handleSwitahEdit(row)"
              >
                + 新增属性值
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                type="danger"
                size="small"
                @click=""
                icon="ele-Delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="save">保存</el-button>
        <el-button
          type="default"
          size="default"
          @click="emits('changeConditionEvent', Condition.SpuList)"
          >取消</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, onMounted, ref } from "vue";
import {
  requestAddSpu,
  requestAllTmList,
  requestBaseSaleAttrList,
  requestSpuImageListById,
  requestSpuSaleAttrListById,
  requestUpdateSpu,
} from "@/api/product";

export default defineComponent({
  name: "SpuForm",
});
</script>

<script setup lang="ts">
import { ElMessage, type UploadProps, type UploadUserFile } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type {
  SpuBaseSaleAttrListType,
  SpuImageListType,
  SpuInfoType,
  SpuSaleAttrItemType,
  SpuSaleAttrListType,
  TardemarkListType,
} from "@/api/product/interface";
import { Condition } from "../type";
/* 获取父组件的数据 */
interface PropsType {
  spuInfo: SpuInfoType;
}
const { spuInfo } = defineProps<PropsType>();
interface EmitsType {
  (
    e: "changeConditionEvent",
    condition: Condition,
    backfillData?: SpuInfoType
  ): void;
}
const emits = defineEmits<EmitsType>();

/* 页面响应式数据 */
const tmList = ref<TardemarkListType>([]);
const saleAttrList = ref<SpuBaseSaleAttrListType>([]);
const spuImageList = ref<SpuImageListType>([]);
const spuSaleAttrList = ref<SpuSaleAttrListType>([]);

/* 发送页面初始数据请求 */
const getInitializingData = async () => {
  // 判断是新增还是修改
  if (spuInfo.id) {
    // 修改 发送四个数据请求
    const promiseOne = requestAllTmList(); // 所有的品牌属性
    const promiseTwo = requestBaseSaleAttrList(); // 所有的销售属性
    const promiseThree = requestSpuImageListById(spuInfo.id); // 所有的图片属性
    const promiseFour = requestSpuSaleAttrListById(spuInfo.id);
    try {
      const result = await Promise.all([
        promiseOne,
        promiseTwo,
        promiseThree,
        promiseFour,
      ]);
      tmList.value = result[0];
      saleAttrList.value = result[1];
      spuImageList.value = result[2];
      spuSaleAttrList.value = result[3];
      // spu 照片墙的逻辑
      spuImageList.value.forEach((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
      // 在 spuSaleAttrList 中添加保存 编辑状态的数据
      spuSaleAttrList.value.forEach((item) => {
        item.isEdit = false;
      });
    } catch (error) {
      ElMessage("初始数据请求失败！");
    }
  } else {
    // 新增发送两个数据请求
    const promiseOne = requestAllTmList(); // 所有的品牌属性
    const promiseTwo = requestBaseSaleAttrList(); // 所有的销售属性
    try {
      const result = await Promise.all([promiseOne, promiseTwo]);
      tmList.value = result[0];
      saleAttrList.value = result[1];
    } catch (error) {
      ElMessage("初始数据请求失败！");
    }
  }
};

onMounted(() => {
  getInitializingData();
});

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const saleAttrListCompute = computed(() => {
  return saleAttrList.value.filter((item1) => {
    //我们给你一个销售属性对象,我想判断当前的spu销售属性列表里有没有和我一样的,如果没有则返回true,如果有则返回false
    return spuSaleAttrList.value.every((item2) => {
      return item2.saleAttrName !== item1.name;
    });
  });
});

const tempSaleAttr = ref("");

const baseUrl = import.meta.env.VITE_API_URL;

const handleAddSaleAttr = () => {
  // 收集表单中的部分数据
  const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(":");
  //我们要把数据插入到spuSaleAttrList,所以我们要拼接一个类似的数据格式才能插入
  const tempSpuSaleAttr = {
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName: saleAttrName,
    spuSaleAttrValueList: [],
  };

  //插入数据到spuSaleAttrList
  spuSaleAttrList.value.push(tempSpuSaleAttr);

  //清空临时数据
  tempSaleAttr.value = "";
};

//保存当前的处在编辑模式的表单元素
const editEle = ref<HTMLInputElement>();
//切换编辑模式的事件函数
const handleSwitahEdit = (row: SpuSaleAttrItemType) => {
  //切换模式
  row.isEdit = true;
  //自动获取焦点
  nextTick(() => {
    editEle.value?.focus();
  });
};
// 输入框失去焦点
const handleSwitahText = (row: SpuSaleAttrItemType) => {
  //切换模式
  row.isEdit = false;
  //获取当前输入的内容
  let inputValue = row.inputValue as string;
  console.log(inputValue);
  //判断当前的内容是否为空
  if (!inputValue.trim()) {
    row.isEdit = false;
    ElMessage.error("添加的属性值为空");
    return;
  }

  //判断输入的内容是否有重复
  const isRepeat = row.spuSaleAttrValueList.some((item) => {
    return item.saleAttrValueName === inputValue;
  });

  if (isRepeat) {
    ElMessage.error("添加的属性值有重复");
    row.isEdit = false;
    row.inputValue = "";
    return;
  }

  //整理以下要添加到row的属性值列表中的数据
  const newSaleAttrValue = {
    //当前所在的销售属性，对应的销售属性id
    baseSaleAttrId: row.baseSaleAttrId,
    //当前销售属性的值
    saleAttrValueName: row.inputValue as string,
    //其他值都不需要，可以不填
  };

  row.spuSaleAttrValueList.push(newSaleAttrValue);

  //最后要清空并切换到按钮模式
  row.isEdit = false;
  row.inputValue = "";
};

const save = async () => {
  //整理 spuImageList 数据
  const newSpuImageList = spuImageList.value.map((item) => {
    if (item.response) {
      return {
        imgUrl: item.response.data as string,
        imgName: item.name as string,
      };
    } else {
      return {
        imgName: item.imgName,
        imgUrl: item.imgUrl,
      };
    }
    // return obj;
  });
  console.log(spuImageList.value);

  //整理SaleAttrvalueList数据，因为里边多了isEdit 和 inputValue两个属性
  spuSaleAttrList.value.forEach((item) => {
    delete item.isEdit;
    delete item.inputValue;
  });

  //把上边整理的两个值添加到spuInfo上
  spuInfo.spuSaleAttrList = spuSaleAttrList.value;
  spuInfo.spuImageList = newSpuImageList;

  //提交数据
  try {
    if (spuInfo.id) {
      //更新操作
      await requestUpdateSpu(spuInfo);
    } else {
      //新增操作
      await requestAddSpu(spuInfo);
    }
  } catch (e) {
    ElMessage.error("新增或者更新数据失败");
  }

  //回到列表页
  emits("changeConditionEvent", Condition.SpuList);
};
</script>
